function htmlspecialchars(text) {
   var chars = Array("<", ">", '"');
   var replacements = Array("&lt;", "&gt;", "&quot;");
   for(var i=0; i<chars.length; i++) {
      var re = new RegExp(chars[i], "gi");
      if(re.test(text)) {
         text = text.replace(chars[i], replacements[i]);
      }
   }
   return text;
}

function highliteLines() {
	$('.tab .list-item').removeClass('list-item-odd list-item-even');
	$('.tab .list-item:not(.hidden)').filter(function(i){return i%2==0}).addClass('list-item-odd');
	$('.tab .list-item:not(.hidden)').filter(function(i){return i%2==1}).addClass('list-item-even');
}

function jqConfirm(question, action) {
    $('<div>'+question+'</div>').dialog({
      title: 'Требуется подтверждение',
      width: 300,
      modal: true,
      buttons: { 
        "Да": function() { $(this).dialog("close"); action(); },
        "Отмена": function() { $(this).dialog("close"); } 
      },
    });
}

function installPackage(name) {
    return actionPackage('install', name);
}

function removePackage(name) {
  jqConfirm('Вы уверены что хотите удалить пакет "'+name+'"?', function () {     
    return actionPackage('remove', name);
  });
  return false
}

function updatePackage(name) {
    return actionPackage('install', name);
}

function actionPackage(action, name) {
  var loader = $('<div><div class="loader" style="height:150px;"></div></div>').dialog({
          title: 'Выполнение...',
          width: 500,
          modal: true,
      });

  $.getJSON("http://"+document.domain+":81/addons/opkg/action.lua?callback=?", {action: action, package: name}, function (result) {
      updateLists();
      loader.dialog("close");
      $('<div class="opkg_output">'+result+'</div>').dialog({
          title: 'Готово',
          width: 500,
          maxHeight: 500,
          modal: true,
          buttons: { "Ок": function() { $(this).dialog("close"); } },
      });
  });
 
  return false
}

function updateLists() {
	var scroll = $(document).scrollTop();
	var t1 = $('#tabs-1').empty();
	var t2 = $('#tabs-2').empty();
	var t3 = $('#tabs-3').empty();
	$('#content').addClass('loader');
	$('#tabs').addClass('hidden');
		$.getJSON("http://"+document.domain+":81/addons/opkg/list.lua?callback=?", function (packages) {
		$('#content').removeClass('loader');
		var keys = [];
		for (var key in packages) {
			keys.push(key);
		}
		keys.sort();
		cnt1 = cnt2 = cnt3 = 0;
		for (var i = 0; i < keys.length; i++)
		{
			pkg_name = keys[i];
			package = packages[pkg_name];
			descr = htmlspecialchars(package.description);
			list_item = $('<div class="list-item"><span class="name">'+pkg_name+'</span> <span class="version">'+package.version+'</span>'+
				'<span class="installed_version">'+(package.installed_version?'<span class="ui-icon ui-icon-check"></span> '+(package.upgradable?package.installed_version:''):'&nbsp;')+'</span>'+
				'<span class="description" title="'+descr+'">'+descr+'</span>'+
				'<span class="actions">'+
				(package.installed_version?'<span onClick="removePackage(\''+pkg_name+'\')" class="ui-icon ui-icon-cancel" title="Удалить"> </span>':'<span onClick="installPackage(\''+pkg_name+'\')" class="ui-icon ui-icon-plus" title="Установить"> </span>')+
				(package.upgradable?'<span onClick="updatePackage(\''+pkg_name+'\')" class="ui-icon ui-icon-refresh" title="Обновить"> </span>':'')+
				'</span></div>');
			t1.append(list_item);
			cnt1++;
			if(package.installed_version) {
				t2.append(list_item.clone());
				cnt2++;
			}
			if(package.upgradable) {
				t3.append(list_item.clone());
				cnt3++;
			}
		}
		$('#tab-header-3 .badge').remove();
		if(cnt3>0) {
			$('#tab-header-3').append('<span class="badge">'+cnt3+'</span>');
		} else {
		    t3.html("<center>Нет пакетов, требующих обновления</center>");
		}
		
		highliteLines();
		$(".list-item").hover(function () {
			$(this).addClass('list-item-hover');
		}, function () {
			$(this).removeClass('list-item-hover');
		});
	  
		$('#tabs').removeClass('hidden');
		$(document).scrollTop(scroll);
	
		});
} 


$(function () {
	$("#tabs").tabs();
	$("input:submit, button").button();  
	$("#update_packages").click(function () {
		actionPackage('update', name);
	});	
	$("#search_input").keyup(function () {
		s = this.value;
		if(s.length<1) {
			$(".list-item").removeClass('hidden');
			highliteLines();
			return;
		}
		$(".list-item").addClass('hidden');
		$(".list-item .name:contains('"+s+"')").parent().removeClass('hidden');
		highliteLines();
	});
	$("#search_clear").click(function () {
		$("#search_input").val('');
		$(".list-item").removeClass('hidden');
		highliteLines();
	});
	updateLists();
});